//
//  MusicPlayViewController.m
//  OurRelax
//
//  Created by 王雅蓉 on 15/6/18.
//  Copyright (c) 2015年 于宾尧. All rights reserved.
//


#define Tablebar 49
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define ScreenWidth [UIScreen mainScreen].bounds.size.width

#import "MusicPlayViewController.h"

#import "MusicPlayTableViewCell.h"

#import "DBCenter.h"

#import "blostView.h"
@interface MusicPlayViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, retain)UITableView *tableview;

@property (nonatomic, retain) UISlider *slider;

@property (nonatomic, retain)UIImageView *playView;

@property (nonatomic, retain)NSTimer *timer;

@property (nonatomic, retain)UIImageView *love;

@property (nonatomic, retain)NSMutableArray *modeArray;
@property (nonatomic, retain)UIImageView *singMode;

@property (nonatomic, assign) NSInteger tapClickCount;

//上一曲
@property (nonatomic, retain) UIImageView *upSing;
//播放
@property (nonatomic, retain)UIImageView *pause;
//下一曲
@property (nonatomic, retain) UIImageView *down;

@property (nonatomic, retain)UIScrollView *scroll;
@property (nonatomic, retain)UIPageControl *pageControl;

@property (nonatomic, retain) UILabel *totalL;
@property (nonatomic, retain) UILabel *durationL;

//这是我改的
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)blostView *MyView;

@end

@implementation MusicPlayViewController

-(void)dealloc
{
    [_tableview release];
    [_slider release];
    [_playView release];
    //[_timer release];
    [_love release];
    [_singMode release];
    [_upSing release];
    [_pause release];
    [_down release];
    [_scroll release];
    
    [_totalL release];
    [_durationL release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.view.backgroundColor = [UIColor lightGrayColor];
    
    [self setUI];
    //self.repeatNum = 0;
    //[Player shareDataHandle].player.delegate = self;
    self.tapClickCount = 0;
    [self setProgress];
}

-(void)setUI
{
    self.arr = [NSMutableArray array];
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64)];
    self.scroll.pagingEnabled = YES;
    self.scroll.delegate = self;
    _scroll.bounces = NO;
    self.scroll.contentOffset = CGPointMake(self.view.bounds.size.width * 1, 0);
    [self.view addSubview:self.scroll];
    self.scroll.contentSize = CGSizeMake(self.view.frame.size.width * 2, self.view.frame.size.height - 64 - 100);
    //UIColor *bg_scroll = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backgroud_hudie3.jpg"]];
    //[self.scroll setBackgroundColor:bg_scroll];
    //    self.scroll.contentOffset = CGPointMake(0, 64);
    [_scroll release];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    [self.scroll addSubview:imageView];
    imageView.backgroundColor = [UIColor yellowColor];
    [imageView release];
    
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    [self.tableview registerClass:[MusicPlayTableViewCell class] forCellReuseIdentifier:@"reuse"];
    [self.scroll addSubview:self.tableview];
    [_tableview release];
    self.playView = [[UIImageView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 100, self.view.frame.size.width, 100)];
    self.playView.userInteractionEnabled = YES;
    self.playView.image = [UIImage imageNamed:@"img_music.png"];
    [self.view addSubview:self.playView];
    [_playView release];
    
    self.MyView = [[blostView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width, 0, self.view.bounds.size.width , self.view.bounds.size.height)];
    
    [self.scroll addSubview:self.MyView];
    [_MyView release];
    
    
    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, 10, 60, 10)];
    self.pageControl.numberOfPages = 2;
    self.pageControl.currentPage = 1;
    //    pageControl.tag = 100;
    self.pageControl.pageIndicatorTintColor = [UIColor colorWithHue:0.9 saturation:0.9 brightness:0.9 alpha:0.5];
    [self.pageControl addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
    [self.playView addSubview:self.pageControl];
    self.playView.backgroundColor = [UIColor whiteColor];
    [_pageControl release];
    
    //进度
    self.durationL = [[UILabel alloc] initWithFrame:CGRectMake(5, 20, 35, 40)];
    self.durationL.textAlignment = NSTextAlignmentCenter;
    _durationL.font = [UIFont systemFontOfSize:12.0];
    _durationL.textColor = [UIColor cyanColor];
    [self.playView addSubview:_durationL];
    [_durationL release];
    
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(40, 35, self.view.frame.size.width - 80, 10)];
#pragma mark 改变进度条图片
    //[slider setThumbImage:[UIImage imageNamed:@"jindu.png"] forState:UIControlStateNormal];
    //[slider setThumbImage:[UIImage imageNamed:@"jindu.png"] forState:UIControlStateHighlighted];
    
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    
    [self.playView addSubview:_slider];
    [_slider release];
    
    self.totalL = [[UILabel alloc] initWithFrame:CGRectMake(_slider.frame.origin.x + _slider.frame.size.width + 5, 20, _durationL.frame.size.width, _durationL.frame.size.height)];
    _totalL.textAlignment = NSTextAlignmentCenter;
    _totalL.font = [UIFont systemFontOfSize:12.0];
    _totalL.textColor = [UIColor cyanColor];
    [self.playView addSubview:_totalL];
    [_totalL release];
    
#warning 播放模式
    //歌曲循环列表
    self.modeArray = [NSMutableArray arrayWithObjects:@"playmodecycle.png", @"playmoderandom.png", @"playmodesinglecycle.png", nil];
    
    self.singMode = [[UIImageView alloc]initWithFrame:CGRectMake(10, 50, 50, 50)];
    self.singMode.userInteractionEnabled = YES;
    UITapGestureRecognizer *singModeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singModeTap)];
    [self.singMode addGestureRecognizer:singModeTap];
    [self.playView addSubview:self.singMode];
    self.singMode.image = [UIImage imageNamed:@"playmodecycle.png"];
    [_singMode release];
    [singModeTap release];
    
    self.upSing = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 4, 55, 30, 30)];
    self.upSing.userInteractionEnabled = YES;
    UITapGestureRecognizer *upSingTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(upSingTap)];
    [self.upSing addGestureRecognizer:upSingTap];
    [self.playView addSubview:self.upSing];
    self.upSing.image = [UIImage imageNamed:@"up.png"];
    [self.upSing release];
    [upSingTap release];
    
    self.pause = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 20, 50, 40, 40)];
    self.pause.userInteractionEnabled = YES;
    UITapGestureRecognizer *pauseTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pauseTap)];
    [self.pause addGestureRecognizer:pauseTap];
    [self.playView addSubview:self.pause];
    self.pause.image = [UIImage imageNamed:@"play.png"];
    [_pause release];
    [pauseTap release];
    
    self.down = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 4 * 3 - 30, 55, 30, 30)];
    [self.playView addSubview:self.down];
    self.down.userInteractionEnabled = YES;
    UITapGestureRecognizer *downTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(downTap)];
    [self.down addGestureRecognizer:downTap];
    self.down.image = [UIImage imageNamed:@"down.png"];
    [self.down release];
    [downTap release];
    
    self.love = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 40, 60, 20, 20)];
    _love.image = [UIImage imageNamed:@"kong.png"];
    _love.userInteractionEnabled = YES;
    UITapGestureRecognizer *loveTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(loveTap)];
    [_love addGestureRecognizer:loveTap];
    [self.playView addSubview:_love];
    [_love release];
    [loveTap release];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"收起" style:UIBarButtonItemStylePlain target:self action:@selector(backButton:)];
}

-(void)setProgress
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)timeAction
{
    if (![Player shareDataHandle].player) {
        return;
    }
    self.slider.value = [Player shareDataHandle].player.progress;
    self.slider.maximumValue = [Player shareDataHandle].player.duration;
    
    NSInteger minutes  = (NSInteger)[Player shareDataHandle].player.duration / 60;
    NSInteger seconds = (NSInteger)[Player shareDataHandle].player.duration % 60;
    NSString *string = [NSString stringWithFormat:@"%02ld:%02ld",minutes,seconds];
    
    _totalL.text =string;
    _totalL.tintColor = [UIColor colorWithRed:244.0f/255.0f green:147.0f/255.0f blue:23.0f/255.0f alpha:1.0f];
    
    NSInteger currentminutes = (NSInteger)[Player shareDataHandle].player.progress / 60;
    NSInteger currentseconds = (NSInteger)[Player shareDataHandle].player.progress % 60;
    NSString *string1 = [NSString stringWithFormat:@"%02ld:%02ld",currentminutes,currentseconds];
    
    _durationL.text =string1;
    _durationL.tintColor = [UIColor colorWithRed:244.0f/255.0f green:147.0f/255.0f blue:23.0f/255.0f alpha:1.0f];
    
    float interval = [Player shareDataHandle].player.duration - [Player shareDataHandle].player.progress;
    if (interval < 6.0 && interval > 0.0) {
    
    //if ([Player shareDataHandle].player.duration < _slider.value) {
        
        [self.timer invalidate];
        if ([TagHandle shareTagHandle].modeStatus == 0) {
            
            //顺序
            [self orderPlaying];
        } else if ([TagHandle shareTagHandle].modeStatus == 1) {
        
            //随机
            [self randomPlaying];
        } else {
        
            //顺序单曲
            [self singlePlaying];
        }
    }
}

#pragma 播放模式
//单曲
-(void)singlePlaying
{
    if ([Player shareDataHandle].playingIndex == [Player shareDataHandle].currentUrlArray.count) {
        
        [Player shareDataHandle].playingIndex = 0;
    }

    NSString *playURL = [[Player shareDataHandle].currentUrlArray objectAtIndex:[Player shareDataHandle].playingIndex];
    NSURL *urlPlaying = [NSURL URLWithString:playURL];
    
    [self setProgress];
    
    [Player shareDataHandle].player.volume = 1.0f;
    [[Player shareDataHandle].player playURL:urlPlaying];
    
    [MusicDetailShareHandle shareListDataHandle].statusMusic = [[MusicDetailShareHandle shareListDataHandle].listShareArray objectAtIndex:[Player shareDataHandle].playingIndex];
}

//随机
-(void)randomPlaying
{
    [Player shareDataHandle].playingIndex = arc4random() % [Player shareDataHandle].currentUrlArray.count;
    
    NSString *playURL = [[Player shareDataHandle].currentUrlArray objectAtIndex:[Player shareDataHandle].playingIndex];
    NSURL *urlPlaying = [NSURL URLWithString:playURL];
    
    [self setProgress];
    
    [Player shareDataHandle].player.volume = 1.0f;
    [[Player shareDataHandle].player playURL:urlPlaying];
    
    [MusicDetailShareHandle shareListDataHandle].statusMusic = [[MusicDetailShareHandle shareListDataHandle].listShareArray objectAtIndex:[Player shareDataHandle].playingIndex];
}

//顺序
-(void)orderPlaying
{
    [Player shareDataHandle].playingIndex ++;
    
    if ([Player shareDataHandle].playingIndex == [Player shareDataHandle].currentUrlArray.count) {
        
        [Player shareDataHandle].playingIndex = 0;
    }
    
    NSString *playURL = [[Player shareDataHandle].currentUrlArray objectAtIndex:[Player shareDataHandle].playingIndex];
    NSURL *urlPlaying = [NSURL URLWithString:playURL];
    
    [self setProgress];
    
    [Player shareDataHandle].player.volume = 1.0f;
    [[Player shareDataHandle].player playURL:urlPlaying];
    
    [MusicDetailShareHandle shareListDataHandle].statusMusic = [[MusicDetailShareHandle shareListDataHandle].listShareArray objectAtIndex:[Player shareDataHandle].playingIndex];
}



-(void)backButton:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

#pragma mark 进度条方法
- (void)sliderAction:(UISlider *)slider
{
    //NSLog(@"%f", slider.value);
    if (![Player shareDataHandle].player) {
        
        return;
    }
    
    [[Player shareDataHandle].player seekToTime:_slider.value];
}

#pragma mark 歌曲模式
- (void)singModeTap
{
    ++self.tapClickCount;
    
    [TagHandle shareTagHandle].modeStatus = self.tapClickCount % 3;
    _singMode.image = [UIImage imageNamed:[_modeArray objectAtIndex:self.tapClickCount % 3]];
}

#pragma mark
- (void)pageAction:(UIPageControl *)pageAction
{
    //NSLog(@"%ld", self.pageControl.numberOfPages);
    _scroll.contentOffset = CGPointMake(self.view.frame.size.width * pageAction.currentPage, - 64);
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.pageControl.currentPage = scrollView.contentOffset.x / self.view.frame.size.width;
}

#pragma mark 上一曲
- (void)upSingTap
{
    //NSLog(@"up");
    [[Player shareDataHandle] lastPlay];
}

#pragma mark 下一曲
- (void)downTap
{
    [[Player shareDataHandle] NextPlay];
}

#pragma mark 播放暂停
- (void)pauseTap
{
    //NSLog(@"pause");
    [TagHandle shareTagHandle].isPlaying = ![TagHandle shareTagHandle].isPlaying;
#pragma 改
    if ([TagHandle shareTagHandle].isPlaying) {
        
        if ([Player shareDataHandle].oldIndex != [Player shareDataHandle].playingIndex) {
            
            [self.timer invalidate];
            [[Player shareDataHandle] PlayForArray];
            [self setProgress];
            
        } else {
            [[Player shareDataHandle].player resume];
        }
        self.pause.image = [UIImage imageNamed:@"pause.png"];
        
    } else {
        
        [[Player shareDataHandle].player pause];
        self.pause.image = [UIImage imageNamed:@"play.png"];
    }

}

#pragma mark 点击收藏
- (void)loveTap
{
    //NSLog(@"love");
    
}

#pragma mark 隐藏tabBar
- (void)viewWillAppear:(BOOL)animated
{
    self.arr = [NSMutableArray array];
    self.tabBarController.tabBar.hidden = YES;
    //中间是我改的
    DBCenter *dataBase = [DBCenter shareInstence];
    [dataBase openDB];
    NSMutableArray *array = [dataBase selectAll];
    
    for (NSInteger i = 0; i < [MusicDetailShareHandle shareListDataHandle].listShareArray.count; i++) {
        for (DataModel *song in array) {
            
            MusicForSonglist *temp = [[MusicDetailShareHandle shareListDataHandle].listShareArray objectAtIndex:i];
            
            if ([song.name  isEqualToString:temp.song_name]) {
                
                
                [self.arr addObject:[NSString stringWithFormat:@"%ld", i]];
                //                NSLog(@"+++++++++++++++");
            }
        }
        
        
        
    }
    //    上面的都是
    

    
    
    
    
    //播放栏
    if ([TagHandle shareTagHandle].isPlaying) {
        
        _pause.image = [UIImage imageNamed:@"pause.png"];
        //[self setProgress];
        
    } else {
        
        _pause.image = [UIImage imageNamed:@"play.png"];
    }
    
    //模式图标
    _singMode.image = [UIImage imageNamed:[_modeArray objectAtIndex:[TagHandle shareTagHandle].modeStatus]];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    //播放栏
    if ([TagHandle shareTagHandle].isPlaying) {
        
        _pause.image = [UIImage imageNamed:@"pause.png"];
        //[self setProgress];
        
    } else {
        
        _pause.image = [UIImage imageNamed:@"play.png"];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [MusicDetailShareHandle shareListDataHandle].listShareArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 155;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicPlayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    //    [self.cell.SoCangBT setBackgroundImage:[UIImage imageNamed:@"musicCircleHeartDefault.png"] forState:UIControlStateNormal];
    
    //初始化选中的单元格背景图片
    for (NSString *str in self.arr) {
        if (indexPath.row == [str integerValue]) {
            [cell.SoCangBT setBackgroundImage:[UIImage imageNamed:@"musicCircleHeartSelected.png"] forState:UIControlStateNormal];
            cell.isSelected = YES;
            break;
        }
        else
        {
            [cell.SoCangBT setBackgroundImage:[UIImage imageNamed:@"musicCircleHeartDefault.png"] forState:UIControlStateNormal];
            cell.isSelected = NO;
        }
    }
    
    //初始化背景图片
    if (cell.isSelected == YES) {
        
        [cell.SoCangBT setBackgroundImage:[UIImage imageNamed:@"musicCircleHeartSelected.png"] forState:UIControlStateNormal];
        
    } else {
        
        [cell.SoCangBT setBackgroundImage:[UIImage imageNamed:@"musicCircleHeartDefault.png"] forState:UIControlStateNormal];
        
    }
    
    //点击收藏改变
    [cell setBlock:^{
        
        NSLog(@">>>>>>点击");
        if (cell.isSelected == NO) {
            NSString *str = [NSString stringWithFormat:@"%ld", indexPath.row];
            [self.arr addObject:str];
            [cell.SoCangBT setBackgroundImage:[UIImage imageNamed:@"musicCircleHeartSelected.png"] forState:UIControlStateNormal];
            NSLog(@"<<<<<<收藏");
            cell.isSelected = YES;
            DBCenter *dataBase = [DBCenter shareInstence];
            [dataBase openDB];
            [dataBase createTable];
            MusicForSonglist *temp = [[MusicDetailShareHandle shareListDataHandle].listShareArray objectAtIndex:indexPath.row];
            NSMutableArray *arrTemp = (NSMutableArray *)temp.url_list;
            NSString *url = [[arrTemp objectAtIndex:0]objectForKey:@"url"];
            DataModel *model = [[DataModel alloc]init];
            model.url = url;
            model.name = temp.song_name;
            model.singer = temp.singer_name;
            [dataBase insertModel:model];
            
            
        }
        else if (cell.isSelected == YES)
        {
            NSString *temp = nil;
            for (NSString *strCom in self.arr) {
                if ([strCom integerValue] == indexPath.row) {
                    temp = strCom;
                }
            }
            [self.arr removeObject:temp];
            [cell.SoCangBT setBackgroundImage:[UIImage imageNamed:@"musicCircleHeartDefault.png"] forState:UIControlStateNormal];
            NSLog(@"????????取消收藏");
            cell.isSelected = NO;
            DBCenter *dataBase = [DBCenter shareInstence];
            [dataBase openDB];
            
            MusicForSonglist *temp2 = [[MusicDetailShareHandle shareListDataHandle].listShareArray objectAtIndex:indexPath.row];
            
            DataModel *model = [[DataModel alloc]init];
            NSLog(@"**********%@", temp2.song_name);
            model.name = temp2.song_name;
            [dataBase delete:model];
            
            
            
        }
        
        
    }];
    cell.playingSonglist = [[MusicDetailShareHandle shareListDataHandle].listShareArray objectAtIndex:indexPath.row];
    
    return cell;
}
#pragma mark 选中某个单元格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //[[Player shareDataHandle].player stop];
    //播放
    [Player shareDataHandle].currentUrlArray = [MusicDetailShareHandle shareListDataHandle].listURLArray;
    
    [Player shareDataHandle].playingIndex = indexPath.row;
    
//    NSLog(@"=============%ld",indexPath.row);
//    NSLog(@"%@",((MusicForSonglist *)[[MusicDetailShareHandle shareListDataHandle].listShareArray objectAtIndex:indexPath.row]).song_name );
    [[Player shareDataHandle] PlayForArray];
    
    //[self setProgress];
    
    if ([TagHandle shareTagHandle].isPlaying) {
        
        _pause.image = [UIImage imageNamed:@"pause.png"];
        
    } else {
        
        _pause.image = [UIImage imageNamed:@"play.png"];
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
